#version 130   
#extension EXT_gpu_shader4 : require  
#extension GL_ARB_texture_rectangle : require  
#extension GL_EXT_geometry_shader4 : require  

//#define USING_ID_BUFFER  // this buffer just stores id info, not positions

#define		POINT_INSIDE			true
#define		POINT_OUTSIDE			false

#ifdef USING_ID_BUFFER
	uniform sampler2DRect idTex;
#endif 

uniform sampler2DRect position;
uniform float nearPlane, farPlane, tang, ratio;
uniform vec3 camPos, X, Y, Z;

// View Frustum Culling (VFC) Radar Method
bool pointInFrustum(vec3 point, out float lod)
{
	float pcz,pcx,pcy,aux;

	//camPos.z -=10.0;
	vec3 v;
	v = point - camPos; 
	pcz = dot(v,Z);

	//lod Selection
	// compute and test the Z coordinate
	if (pcz > farPlane || pcz < (nearPlane-2.0))
		return POINT_OUTSIDE;
	// compute and test the Y coordinate
	
	pcy = dot(v,Y);
	aux = pcz * tang;
	//aux = camPos.y + 50.0;
	if (pcy > (aux+1.0) || pcy < -(aux+1.0))
		return POINT_OUTSIDE;
	// compute and test the X coordinate
	pcx = dot(v,X);
	aux = aux * ratio;
	//aux = camPos.x + 50.0;
	if (pcx > (aux+1.0) || pcx < -(aux+1.0))
		return POINT_OUTSIDE;

	// 4 LODs 
	//lod = step(0.001, pcz) + step(farPlane/40.0, pcz)  + step(farPlane/12.0, pcz) + step(farPlane/4.0, pcz); 
	// For 3 LODs:
	lod = step(0.001, pcz) + step(farPlane/10.0, pcz)  + step(farPlane/4.0, pcz); 

	return true;	
}

void main ()
{
	float lod=0.0;
	vec2 texcoord = gl_PositionIn[0].xy;
	vec4 pos = texture2DRect(position, texcoord);

#ifdef	USING_ID_BUFFER
	vec4 ids = texture2DRect(idTex, texcoord);
#endif
	
	if (pointInFrustum(pos.yzx,lod))
	{
		pos.z = pos.w;  //direction
#ifdef USING_ID_BUFFER
		pos.x = gl_TexCoordIn[0][0].x; //glVertexId
		pos.y = ids.z; // Animation id  
#endif	
		//gl_FrontColor = vec4(lod/3.0,0,0,1);  // div 3 for display purposes
		pos.w = lod;

		gl_Position = pos;
		EmitVertex();
		EndPrimitive();	
	}
}

